package com.mylhyl.zxing.scanner.camera.open;

import ohos.agp.graphics.SurfaceOps;
import ohos.media.camera.device.Camera;
import ohos.media.camera.device.CameraConfig;
import ohos.media.camera.device.CameraStateCallback;
import ohos.media.camera.device.FrameConfig;

import static ohos.media.camera.device.Camera.FrameConfigType.FRAME_CONFIG_PREVIEW;

public class CameraStateCallbackImpl extends CameraStateCallback {
    private static final String TAG = CameraStateCallbackImpl.class.getName();

    private Camera mCamera;
    private SurfaceOps mSurfaceOps;

    public CameraStateCallbackImpl(SurfaceOps surfaceOps) {
        this.mSurfaceOps = surfaceOps;
    }

    @Override
    public void onCreated(Camera camera) {
        this.mCamera = camera;
        CameraConfig.Builder cameraConfigBuilder = camera.getCameraConfigBuilder();
        if (cameraConfigBuilder == null) {
            return;
        }
        // 配置预览的Surface
        cameraConfigBuilder.addSurface(mSurfaceOps.getSurface());
        try {
            // 相机设备配置
            camera.configure(cameraConfigBuilder.build());
        } catch (IllegalArgumentException e) {
        } catch (IllegalStateException e) {
        }
    }

    @Override
    public void onConfigured(Camera camera) {
        // 配置相机设备
        // 获取预览配置模板
        FrameConfig.Builder frameConfigBuilder = camera.getFrameConfigBuilder(FRAME_CONFIG_PREVIEW);
        // 配置预览Surface
        frameConfigBuilder.addSurface(mSurfaceOps.getSurface());
        FrameConfig previewFrameConfig = frameConfigBuilder.build();
        try {
            // 启动循环帧捕获
            int triggerId = camera.triggerLoopingCapture(previewFrameConfig);
        } catch (IllegalArgumentException e) {
        } catch (IllegalStateException e) {
        }
    }

    @Override
    public void onPartialConfigured(Camera camera) {
        // 当使用了addDeferredSurfaceSize配置了相机，会接到此回调
    }

    @Override
    public void onReleased(Camera camera) {
        // 释放相机设备
    }

    public Camera getCamera() {
        return mCamera;
    }
}